import type ExcelJS from 'exceljs';
import { outputFileSync } from 'fs-extra';
import { resolve } from 'path';

export function attendanceStatisticsExcelToJson(workbook: ExcelJS.Workbook) {
  const worksheet = workbook.getWorksheet(4);

  if (!worksheet) throw new Error('解析工作表失败');

  const cols = [
    { title: '姓名', address: 'a', prop: 'name' },
    { title: '考勤组', address: 'b', prop: 'group' },
    { title: '部门', address: 'c', prop: 'department' },
    { title: 'id', address: 'f', prop: 'dingId' },
    { title: '出勤班次', address: 'g', prop: 'attendanceClass' },
    { title: '考勤时间', address: 'h', prop: 'workDate' },
    { title: '班次', address: 'i', prop: 'planDetail' },
    { title: '应出勤天数', address: 'j', prop: 'shouldAttendanceDays' },
    { title: '补卡次数', address: 'k', prop: 'makingUpLackTimes' },
    { title: '上班1打卡时间', address: 'l', prop: 'onDutyUserCheckTime' },
    { title: '上班1打卡结果', address: 'm', prop: 'onDutyUserCheckResult' },
    { title: '下班1打卡时间', address: 'n', prop: 'offDutyUserCheckTime' },
    { title: '下班1打卡结果', address: 'o', prop: 'offDutyUserCheckResult' },
    { title: '出勤天数', address: 'y', prop: 'attendanceDays' },
    { title: '休息天数', address: 'z', prop: 'attendanceRestDays' },
    { title: '工作时长', address: 'aa', prop: 'attendanceWorkTime' },
    { title: '迟到次数', address: 'ab', prop: 'lateTimes' },
    { title: '迟到时长', address: 'ac', prop: 'lateMinute' },
    { title: '严重迟到次数', address: 'ad', prop: 'seriousLateTimes' },
    { title: '严重迟到时长', address: 'ae', prop: 'seriousLateMinute' },
    { title: '早退次数', address: 'ag', prop: 'leaveEarlyTimes' },
    { title: '早退时长', address: 'ah', prop: 'leaveEarlyMinute' },
    { title: '上班缺卡次数', address: 'ai', prop: 'onWorkLackCardTimes' },
    { title: '下班缺卡次数', address: 'aj', prop: 'offWorkLackCardTimes' },
    { title: '旷工天数', address: 'ak', prop: 'absenteeismDays' },
  ] as const;

  const startCellNumber = 5;
  const data: Record<(typeof cols)[number]['prop'], any>[] = [];

  worksheet.eachRow({ includeEmpty: true }, async (row, rowNumber) => {
    if (rowNumber >= startCellNumber) {
      const cellArr = <(typeof data)[number]>{};
      cols.forEach((col) => {
        const cell = worksheet.getCell(
          col.address.toLocaleUpperCase() + rowNumber,
        );

        cellArr[col.prop] = cell.value;
      });
      data.push(cellArr);
    }
  });

  // 导出文件
  const name = resolve(
    'uploads/attendance-statistics' + '/' + Date.now() + '.json',
  );
  outputFileSync(name, JSON.stringify(data, null, 2));

  return data;
}
